package app.modules.security.persistence.dao;

import app.modules.security.dto.web.permission.WebPermissionDTO;
import app.modules.security.dto.web.permission.WebPermissionQueryDTO;
import app.modules.security.persistence.mapper.PermissionMapper;
import app.modules.security.util.conversion.PermissionConvertUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jasmine.framework.common.util.CheckUtil;
import jasmine.framework.common.util.CollectionUtil;
import jasmine.framework.common.util.StringUtil;
import jasmine.framework.database.mybatisplus.dao.BaseI18nEntityDAO;
import jasmine.framework.database.mybatisplus.wrapper.LambdaQueryWrapperWithI18n;
import jasmine.security.rbac.model.SecPermission;
import org.springframework.stereotype.Repository;

import javax.annotation.Nullable;
import java.util.Collection;
import java.util.List;

/**
 * @author mh.z
 */
@Repository
public class PermissionDAO extends BaseI18nEntityDAO<PermissionMapper, SecPermission> {

    /**
     * 分页查询权限
     *
     * @param queryDTO
     * @param page
     * @return
     */
    public List<WebPermissionDTO> pageWebPermissionDTOsByCond(WebPermissionQueryDTO queryDTO, Page page) {
        CheckUtil.notNull(queryDTO, "queryDTO null");
        CheckUtil.notNull(page, "page null");
        LambdaQueryWrapperWithI18n<SecPermission> wrapper = LambdaQueryWrapperWithI18n.wrapper();

        String permissionCode = queryDTO.getPermissionCode();
        wrapper.like(StringUtil.isNotEmpty(permissionCode), SecPermission::getPermissionCode, permissionCode);
        String permissionName = queryDTO.getPermissionName();
        wrapper.likeWithI18n(StringUtil.isNotEmpty(permissionName), SecPermission::getPermissionName, permissionName);
        String remark = queryDTO.getRemark();
        wrapper.likeWithI18n(StringUtil.isNotEmpty(remark), SecPermission::getRemark, remark);
        wrapper.orderByAsc(SecPermission::getPermissionCode);

        Page<SecPermission> pageResult = baseMapper.selectPageWithI18n(page, wrapper);
        List<SecPermission> recordList = pageResult.getRecords();
        List<WebPermissionDTO> returnList = PermissionConvertUtil.secPermission2WebPermissionDTO(recordList);

        return returnList;
    }

    /**
     * 根据权限代码统计
     *
     * @param permissionCode
     * @param excludeIds
     * @return
     */
    public long countByPermissionCode(String permissionCode, @Nullable Collection<Long> excludeIds) {
        LambdaQueryWrapper<SecPermission> wrapper = Wrappers.lambdaQuery();

        wrapper.eq(SecPermission::getPermissionCode, permissionCode);
        wrapper.notIn(CollectionUtil.isNotEmpty(excludeIds), SecPermission::getId, excludeIds);

        return baseMapper.selectCount(wrapper);
    }

}
